<?php


namespace App;

use Noodlehaus\Config;
use Noodlehaus\Parser\Json;

class Conf
{
    /**
     * @var Config
     */
    private $conf;

    private $confIniDefault = [
        'qiniu' => ['accessKey' => "22_LmfhJPo4QYtOVw0WKYr80PnaWAZcJpodf2UXX", 'secretKey' => 'qoZ9tnpjCey-9JSyQc4BmWzMJcI_MKtWswKMhXg7', 'bucket' => 'test', 'domin' => "http://qiniu.gfrtrttweet.com/"],
        'tenxxun' => ['accessKey' => "AKIDT1MiqqijOJK9nDqfBusAJGlL6j6J4O9i", 'secretKey' => 'HPQCvQlCB1lRv53sYm283uRp359yeLHd', 'bucket' => '']
    ];

    private static $instance = null;

    /**
     * ScanList constructor.
     */
    private function __construct()
    {
        $this->init();
    }

    private function init()
    {
        if (!file_exists(APP_PATH . 'conf.ini')) {
            touch(APP_PATH . 'conf.ini');
            $this->writeINI($this->confIniDefault, APP_PATH . 'conf.ini', true);
        }
        $conf = Config::load(APP_PATH . 'conf.ini');
        $this->conf = $conf;
    }

    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    public static function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getConf($key)
    {
        return $this->conf->get($key);
    }


    public static function get($key)
    {
        return self::getInstance()->getConf($key);
    }


    public function writeINI($assoc_arr, $path, $has_sections = FALSE)
    {
        $content = "";
        if ($has_sections) {
            foreach ($assoc_arr as $key => $elem) {
                $content .= "[" . $key . "]\n";
                foreach ($elem as $key2 => $elem2) {
                    if (is_array($elem2)) {
                        for ($i = 0; $i < count($elem2); $i++) {
                            $content .= $key2 . "[] = \"" . $elem2[$i] . "\"\n";
                        }
                    } else if ($elem2 == "") $content .= $key2 . " = \n";
                    else $content .= $key2 . " = \"" . $elem2 . "\"\n";
                }
            }
        } else {
            foreach ($assoc_arr as $key => $elem) {
                if (is_array($elem)) {
                    for ($i = 0; $i < count($elem); $i++) {
                        $content .= $key . "[] = \"" . $elem[$i] . "\"\n";
                    }
                } else if ($elem == "") $content .= $key . " = \n";
                else $content .= $key . " = \"" . $elem . "\"\n";
            }
        }
        if (!$handle = fopen($path, 'w')) {
            return false;
        }
        if (!fwrite($handle, $content)) {
            return false;
        }
        fclose($handle);
        return true;
    }

}